package com.ww.algorithm.search.binarydiv

class Solution1 {

    /**
     * 左闭右闭
     */
    fun search(nums: IntArray, target: Int): Int {
        var left = 0
        var right = nums.size - 1

        // 使用左闭右闭
        while (left <= right) {
            val middle = (left + right) / 2
            // target在左边
            if (nums[middle] > target) right = middle - 1
            else if (nums[middle] < target) left = middle + 1
            else return middle
        }
        return -1
    }
}

class Solution2 {
    /**
     * 左闭右开
     */
    fun search(nums: IntArray, target: Int): Int {
        var left = 0
        var right = nums.size
        while (left < right) {
            val middle = (left + right) / 2
            if (nums[middle] > target) left = middle
            else if (nums[middle] < target) right = middle + 1
            else return middle
        }
        return -1
    }
}


fun main(args: Array<String>) {
    val solution = Solution1()
    println(solution.search(intArrayOf(1,2,3,4), 3))

    val solution2 = Solution2()
    println(solution2.search(intArrayOf(1,2,3,4), 3))
}
























































